import { getConfigDetailApi, updateConfigApi } from '@/services/api';
import { ProCard, ProDescriptions } from '@ant-design/pro-components';
import { useAccess } from '@umijs/max';
import { useRequest } from 'ahooks';
import { Button, Input, Space, message } from 'antd';
import React, { useState } from 'react';

const Setting: React.FC = () => {
  const [value, setValue] = useState('');

  const { system_config_permissions_list_edit } = useAccess() as any;

  const { data, run, loading } = useRequest(
    async () => {
      const _res = await getConfigDetailApi(1);
      return _res?.data;
    },
    {
      onSuccess: (res) => {
        setValue(res?.token);
      },
    },
  );

  //   是否编辑状态
  const [isEdit, setEdit] = useState(false);

  return (
    <ProCard loading={loading}>
      <ProDescriptions
        labelStyle={{
          width: 300,
        }}
        extra={
          !system_config_permissions_list_edit ? null : (
            <Space>
              {isEdit ? (
                <>
                  <Button
                    onClick={() => {
                      setEdit(false);
                    }}
                  >
                    取消
                  </Button>
                  <Button
                    type="primary"
                    onClick={async () => {
                      try {
                        await updateConfigApi(1, { token: value });
                        run();
                        message.success('修改成功');

                        setEdit(false);
                      } catch (error) {}
                    }}
                  >
                    保存
                  </Button>
                </>
              ) : (
                <Button
                  type="primary"
                  onClick={() => {
                    setEdit(true);
                  }}
                >
                  编辑
                </Button>
              )}
            </Space>
          )
        }
        bordered
        column={1}
        title="系统配置"
      >
        <ProDescriptions.Item label="token">
          {isEdit ? (
            <Input
              value={value}
              onChange={(e) => {
                setValue(e.target.value);
              }}
            />
          ) : (
            data?.token
          )}
        </ProDescriptions.Item>
      </ProDescriptions>
    </ProCard>
  );
};
export default Setting;
